package com.aiit.shiro;

import com.aiit.pojo.SysUser;
import com.aiit.service.SysPermissionService;
import com.aiit.service.SysRoleService;
import com.aiit.service.SysUserService;
import com.alibaba.druid.util.Base64;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService  sysUserService;
    @Autowired
    private SysRoleService  sysRoleService;
    @Autowired
    private SysPermissionService  sysPermissionService;
    //获取用户的权限数据
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) throws UnauthorizedException{
        //能进入到这里，表示账号已经通过验证了
        String userName =(String) principalCollection.getPrimaryPrincipal();
        Set<String> permissions;
        Set<String> roles;
        try{
            //通过service获取角色和权限
            permissions = sysPermissionService.listPermissions(userName);
            roles= sysRoleService.listRoles(userName);
        }catch(Exception e){
          throw new UnauthorizedException();
        }
        //授权对象
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        //把通过service获取到的角色和权限放进去
        s.setStringPermissions(permissions);
        s.setRoles(roles);
        return s;
    }
    //获取用户的凭证（密码）数据
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) authenticationToken;
        String userName = authenticationToken.getPrincipal().toString();
        String password = new String(t.getPassword());
        //获取数据库中的密码
//        String passwordInDB = sysUserService.getPasswordByUserName(userName);

        SysUser sysUser = sysUserService.getUserByUserName(userName);
        //如果为空就是账号不存在，如果不相同就是密码错误，但是都抛出AuthenticationException，而不是抛出具体错误原因，免得给破解者提供帮助信息
        if (null == sysUser){
            return null;
         }
//        SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(sysUser.getUsername(),sysUser.getPassword(),getName());

        //认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :databaseRealm    ByteSource.Util.bytes(sysUser.getSalt())

//        ByteSource bytes = ByteSource.Util.bytes(Base64.base64ToByteArray(sysUser.getSalt()));

        SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(sysUser.getUsername(),sysUser.getPassword(),ByteSource.Util.bytes(sysUser.getSalt()),getName());
        return a;

    }
}
